<template>
  <div class="layout-container">
    <div class="layout-container-form" style="flex-direction: column">
      <div class="layout-container-form-search">
        <el-row style="text-align: left">
          <el-col :span="24">
            <el-form label-width="90px" :inline="true">
               <el-form-item label="查询数据类型：" style="width:100%" label-width="120px" >
                    <el-select v-model="moneyOrGoods.index" placeholder="请选择数据类型" style="width: 392px" clearable @clear="clearStatus"
                    @change="changeMode">
                    <el-option v-for="item in moneyOrGoods.list" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
              </el-form-item>
              <el-form-item label="姓名：">
                <el-input v-model="query.name" placeholder="请输入姓名" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
               <el-form-item label="下单时间：">
                  <el-date-picker v-model="query.apply_time" type="datetimerange" prefix-icon="el-icon-date"
                    range-separator="→" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                    start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%" @change="changeEffectiveTime" />
                </el-form-item>
              <el-form-item label="搜索金额：">
                <el-input v-model="query.apply_amount" placeholder="请输入团队编号" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="用户ID：">
                <el-input v-model="query.user_id" placeholder="请输入用户ID" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              
             <el-form-item label="状态：">
                <el-select v-model="query.status" placeholder="请选择状态" style="width: 100%" 
                    @change="changeStatus">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
               <el-form-item label="物品名称：">
                <el-input v-model="query.product_name" placeholder="请输入物品名称" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="支付宝账号：">
                <el-input v-model="query.alipay_account" placeholder="请输入支付宝账号" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="团队编号：">
                <el-input v-model="query.team_number" placeholder="请输入团队团队编号" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
               <el-form-item label="订单编号：">
                <el-input v-model="query.order_id" placeholder="请输入订单编号" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item style="width:100%;text-align:right">
                <el-button class="search-btn" style="margin-left: 8px" @click="resetSearch">{{
                    $t("message.common.reset")
                }}</el-button>
                <el-button type="primary" class="search-btn" @click="getTableData(true)">{{ $t("message.common.search")
                }}</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div class="layout-container-opt" style="">
         <div style="padding:0 20px 0 20px">
            <el-checkbox v-model="checkAll" label="1" @change="changeAll">全选</el-checkbox>
        </div>
        <!-- <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="selectData.length > 0 ? 'primary' : ''" :disabled="selectData.length === 0"
          :loading="exportBatchLoading" @click="exportExcelFun">
          批量导出申请记录
        </el-button> -->
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type=" 'primary'" :disabled="selectData.length === 0"
          :loading="exportBatchLoading" @click="exportExcelFun">
          导出所有选择数据
        </el-button>
         <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'" 
          :loading="exportBatchLoading" @click="handleBatchImport">
          批量上传审核结果
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="selectData.length > 0 ? 'primary' : ''" :disabled="selectData.length === 0"
          :loading="exportBatchLoading" @click="handleOpt({},0)">
          批量删除所选数据
        </el-button>
        <el-button class="search-btn" icon="el-icon-refresh-right" style="position:absolute;right:0;bottom:8px;"
          @click="getTableData(true)">{{ $t("message.common.refresh") }}</el-button>
      </div>
    </div>
    <div class="layout-container-table" style="height:600px">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true"
       :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
            <el-table-column 
            v-for="(item,index) in columns" :type="item.type" :key="index"
            :label="item.label"
            :width="item.width"
            :property="item.property">
                <template #default="scope" v-if="item.input">
                    <el-input v-model="scope.row.dict_number" placeholder="" />
                </template>
                <template #default="scope" v-else-if="item.copy">
                    <span>{{scope.row[item.property]}} '
                        <el-icon class="cup" v-copy="scope.row[item.property]"  color="#409eff"><DocumentCopy /></el-icon>
                    </span>
                </template>
                <template #default="scope" v-else-if="item.tooltip">
                    <el-popover
                        placement="bottom"
                        @show="(()=>{getHistoryPeopleLevel(scope.row)})"
                        :disabled="scope.row[item.property] ==''?true:false"
                        trigger="hover">
                        <div slot="content">
                            <template v-if="item.property == 'team_people_level'">
                                <div v-for="(el, i) in historyPeopleLevelArr" :key="i">
                                    {{el}}
                                </div>
                            </template>
                            <div v-else-if="item.property == 'review_details'" v-html="scope.row[item.property]">
                            </div>
                            <template v-else>
                                {{scope.row[item.property]}}
                            </template>
                            
                        </div>
                        <template #reference>
                            
                             <template v-if="item.property == 'remark' || item.property == 'delivery_address' || item.property == 'review_details'">
                                <span v-if="scope.row[item.property] == ''">无</span>
                                <el-button v-else type="text">查看</el-button>
                            </template>
                             <div v-else-if="item.property == 'status'">
                                <el-button type="text" style="color:#e6a23c"  v-if="scope.row.status == 0" >审核中</el-button>
                                <el-button type="text" style="color:#67c23a"  v-if="scope.row.status == 1">已通过</el-button>
                                <el-button type="text" style="color:#f56c6c"  v-if="scope.row.status == 2" >审核不通过</el-button>
                            </div>
                            <el-button v-else type="text">{{scope.row[item.property]}}</el-button>
                        </template>
                    </el-popover>
                </template>
                <template  #default="scope" v-else>
                    <template v-if="item.property">
                        <el-input
                            v-if="scope.row.showInput" 
                            v-model="scope.row[item.property]" 
                            placeholder="" />
                        <span v-else :class="[item.classes]">{{scope.row[item.property]}}</span>
                    </template>
                </template>
                
            </el-table-column>
            <!-- <el-table-column label="审核详情" width="180">
                <template #default="scope">
                    <el-button type="text" style="color:#e6a23c"  v-if="scope.row.status == 0" @click="handleOpt(scope.row,2,scope.$index)">审核中</el-button>
                    <el-button type="text" style="color:#67c23a"  v-if="scope.row.status == 1" @click="handleOpt(scope.row,3,scope.$index)">已通过</el-button>
                    <el-button type="text" style="color:#f56c6c"  v-if="scope.row.status == 2" @click="handleOpt(scope.row,4,scope.$index)">审核不通过</el-button>
                    
                </template>
            </el-table-column> -->
            <el-table-column label="提示文本" prop="review_desc" width="180">
                <template  #default="scope">
                    <div>
                         {{scope.row.review_desc}}
                    </div>
                </template>
               
            </el-table-column>
      </Table>
    </div>
      <!-- 上传文件弹出框组件 -->
        <BatchImportDialog 
        v-if="uploadObj.visible"
        :visible="uploadObj.visible"
        :title="uploadObj.title"
        :uploadObj="uploadObj"
        @closeUploadDialog="closeUploadDialog"
        @refreshTable="refreshTable"/>
  </div>
</template>

<script lang="ts">
import { defineComponent} from "vue";
import Copy from '@/directive/copy'
  export default defineComponent({
    directives: {
      Copy
    },
  
    setup(props) {
    }
  })
</script>
<script setup lang="ts">
import {  ref, reactive } from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox ,ElIcon } from "element-plus";
import BatchImportDialog from "@/components/uploadFile/batchImportDialog.vue";
import {
  DocumentCopy
} from '@element-plus/icons-vue'


import Table from "@/components/table/index.vue";
import {
  teamPage,historyPeopleLevel,teamEdit
} from "@/api/team.ts";
import {
  cashReviewRecords,productReviewRecords,exportCashReviewRecords,exportProductReviewRecords,batchDeleteOrder
} from "@/api/exchange.ts";
import { dateFormat, intervalTime, calculateDiffTime } from "@/utils/index.ts";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { ossPrefix,ossPrefixNew } from "@/utils/index.ts";
const router = useRouter();
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);

// 存储搜索用的数据
const query = reactive({
  name: '', // string
  team_number: '', // string
  status: -1, // string
  apply_time: [], // array[string]
  apply_amount:'',
  user_id: '', // string
  product_name:'',
  alipay_account:'',
  order_id:'',
});
// 状态 0 未生效 1已完成 2 已领取 3指派中 4返修中 5 闲置中 6 已作废
const statusOptions = ref([
   {
    label: '全部',
    value: -1
  },
  {
    label: '审核中',
    value: 0
  },
  {
    label: '已通过',
    value: 1
  },{
    label: '审核不通过',
    value: 2
  },
])
const moneyOrGoods = reactive({
   index:0,
   cmd:cashReviewRecords,
   export:exportCashReviewRecords,
   list:[
    {
        label: '现金申请记录',
        value: 0,
        cmd:cashReviewRecords,
        export:exportCashReviewRecords
    },
    {
        label: '商品申请记录',
        value: 1,
        cmd:productReviewRecords,
        export:exportProductReviewRecords
    },
   ]
})
// 状态change事件
const changeStatus = () => {
  getTableData(true);
}
// 状态change事件
const changeMode = () => {
  columns.value = moneyOrGoods.index == 0?columns1:columns2
  moneyOrGoods.cmd = moneyOrGoods.list[moneyOrGoods.index].cmd
  moneyOrGoods.export = moneyOrGoods.list[moneyOrGoods.index].export
  getTableData(true);
}
// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});
// 重置
const resetSearch = () => {
    query.name = ''//
    query.team_number = ''//, // string
    query.status = -1//, // string
    query.user_id = ''//, // string
    query.apply_time = []//, // string
    query.product_name = ''//, // string
    query.alipay_account = ''// // string
    query.status = -1
    query.order_id = ''
    getTableData(true);
}
const columns = ref([])
const columns1 = reactive([
    {
        label:'序号',
        property:'Id', 
        width:'55',
    },
    {
        label:'申请时间',
        property:'apply_time',
    },{
        label:'订单号',
        property:'order_id',
    },{
        label:'支付宝账号',
        property:'alipay_account',
    },{
        label:'申请人姓名',
        property:'name',
        classes:'blue',
    },{
        label:'实际到账金额',
        property:'received_amount',
    },{
        label:'纳税金额',
        property:'tax_amount',
    },{
        label:'兑换金额',
        property:'total_amount',
    },{
        label:'扣除芝草',
        property:'balance',
    },{
        label:'申请备注',
        property:'remark',
        tooltip:true,
    },{
        label:'用户昵称',
        property:'nick_name',
        classes:'blue',
    },{
        label:'用户ID',
        property:'user_id',
    },{
        label:'用户身份证',
        property:'id_card_number',
    },{
        label:'用户手机号',
        property:'phone',
    },{
        label:'用户邮箱',
        property:'email',
    },{
        label:'所属团队',
        property:'team_number',
    },{
        label:'团长姓名',
        property:'team_user_name',
    },{
        label:'团长昵称',
        property:'tl_nick_name',
    },{
        label:'团长ID',
        property:'team_user_id',
    },{
        label:'团长手机号',
        property:'tl_phone',
    },{
        label:'团长邮箱',
        property:'tl_email',
    },{
        label:'审核详情',
        property:'review_details',
        tooltip:true,
    }
]);
columns.value = columns1
const columns2 = reactive([
    {
        label:'序号',
        property:'Id', 
        width:'55',
    },
    {
        label:'申请时间',
        property:'apply_time',
    },{
        label:'订单号',
        property:'order_id',
    },{
        label:'支付宝账号',
        property:'alipay_account',
    },{
        label:'申请人姓名',
        property:'name',
        classes:'blue',
    },{
        label:'申请物品名称',
        property:'product_name',
    },{
        label:'申请数量',
        property:'number',
    },{
        label:'扣除芝草',
        property:'balance',
    },{
        label:'申请备注',
        property:'remark',
        tooltip:true,
    },{
        label:'用户昵称',
        property:'nick_name',
        classes:'blue',
    },{
        label:'用户地址',
        property:'delivery_address',
        tooltip:true,
    },{
        label:'用户ID',
        property:'user_id',
    },{
        label:'用户身份证号',
        property:'id_card_number',
    },{
        label:'用户手机号',
        property:'phone',
    },{
        label:'用户邮箱',
        property:'email',
    },{
        label:'所属团队',
        property:'team_number',
    },{
        label:'团长姓名',
        property:'team_user_name',
    },{
        label:'团长昵称',
        property:'tl_nick_name',
    },{
        label:'团长ID',
        property:'team_user_id',
    },{
        label:'团长手机号',
        property:'tl_phone',
    },{
        label:'团长邮箱',
        property:'tl_email',
    },{
        label:'审核详情',
        property:'review_details',
        tooltip:true,
    }
]);
const loading = ref(false);
const tableData = ref([]);

const getParams = ()=>{
    let obj = {
        page: page.index,
        page_size: page.size,
        name: '', // string
        team_number: '', // string
        status: -1, // string
        apply_time: [], // array[string]
        apply_amount:'',
        user_id: '', // string
        product_name:'',
        alipay_account:'',
        ...query
    }
    obj.status =  obj.status == undefined ? -1 : obj.status +''
    Object.keys(obj).map(item => {
        if(obj[item] == ''){
            delete obj[item]
        }
    })
    if(obj.apply_time && obj.apply_time.length){
        obj.apply_time_start = obj.apply_time[0]
        obj.apply_time_end = obj.apply_time[1]
        delete obj.apply_time
    }
    if(obj.status == -1){
        delete obj.status
    }
    return obj
}



const table = ref()
const checkAll = ref(false)
const changeAll = (e:any)=>{
    console.log(checkAll.value)
    if(e){
        if(selectData.value.length == tableData.value.length) return
        table.value.$refs.systemTable.toggleAllSelection()
    }else{
        selectData.value = [];
        table.value.$refs.systemTable.clearSelection()
    }
}
// 勾选数据
const selectData = ref([]); // 系统id
const handleSelectionChange = (data: any) => {
  selectData.value = [];
  if(data.length){
    if(data.length != tableData.value.length){
      checkAll.value = false
    }
    data.forEach((item: any) => {
      selectData.value.push(item.order_id);
    });
  }
};



// 获取表格数据
// params <init> Boolean ，默认为false，用于判断是否需要初始化分页
const getTableData = (init: Boolean) => {
  loading.value = true;
  if (init) {
    page.index = 1;
  }
  let params = getParams()
  const test = ()=>{return moneyOrGoods.cmd}
  test()(params)
    .then((res: any) => {
      
      let data = res.data.list;
      data.forEach((d: any,index:any) => {
        d.loading = false;
        d.Id = params.page * (index + 1) 
        d.review_details  = d.review_details?d.review_details.replaceAll(',','<br />'):''
        d.apply_time = dateFormat(d.apply_time)
      });

      tableData.value = data;
      page.total = Number(res.data.count);
      if(checkAll.value){
          changeAll(true)
      }
    })
    .catch(() => {
      tableData.value = [];
      page.index = 1;
      page.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};
const tooltipType = ref('')
const historyPeopleLevelArr = ref([]);
const getHistoryPeopleLevel = (row:any)=>{
    if(row.property == ''){
        historyPeopleLevel({id:row.Id}).then(res => {
            if(res.code == 200){
                historyPeopleLevelArr.value =res.data.list 
            }else{
                ElMessage.success(res.message);
            }
        })
    }
    
}
const copyUrl = (row:any)=>{
    historyPeopleLevel({id:row.Id}).then(res => {
        if(res.code == 200){
            historyPeopleLevelArr.value =res.data.list 
        }else{
            ElMessage.success(res.message);
        }
    })
}
// 操作
const handleOpt = (row: any, type: Number,index:Number) => {
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      // 详情
      let par = {
       
      }
     if(type == 0){// 入职
        par = {
          ids:[],
          ...getParams()
        }
        if(!checkAll.value){
          par.ids = selectData.value
        }
       
        batchDeleteOrder(par).then(res => {
          if(res.code == 200){
              ElMessage.success('操作成功！');
              getTableData()
          }else{index
            ElMessage.success(res.message);
          }
        })
        return
      }
      setProfileUdate(par,row,index)
    })
    .catch(() => { });
};

const setProfileUdate = (par:any,row:Object,index:Number)=> {
    teamEdit(par).then(res => {
        if(res.code == 200){
            debugger
            ElMessage.success('操作成功！');
            tableData.value.splice(index,1,{...row,status:par.status})
        }else{index
           ElMessage.success(res.message);
        }
    })
}

// 导出题目答案与表格
const exportBatchLoading = ref(false);
const exportSingleLoading = ref(false);
const exportExcelFun = () => {
  exportBatchLoading.value = true;
  exportExcelPost(selectData.value)
}
// 导出通用函数
const exportExcelPost = (order_ids: any) => {
  let data = {
    order_ids:'' , // array[interger]
    ... getParams(),
  }
  delete data.page
  delete data.page_size
  let str = ""
  if(checkAll.value){
    delete data.order_ids
  }else{
    if(order_ids){
      order_ids.map(item => {
        str += "'"+item+"'," 
      })
    }
    data.order_ids = str
  }
  const test = ()=>{return moneyOrGoods.export}
  test()(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('导出成功');
      window.open(res.data);
    }
  }).finally(() => {
    exportBatchLoading.value = false;
    exportSingleLoading.value = false;
  })
}
// 批量导入用户
const uploadObj = reactive({
  fileType: ['.xls', '.xlsx'],
  accept: '.xls, .xlsx', // 文件上传类型
  multiple: false, // 是否支持多选
  visible: false,
  title: '',
  url: '', // 批量导入用户接口地址
  type:'team',
  downloadObj: {
    name: '',
    url: ''
  }
});
const closeUploadDialog = ()=>{
    uploadObj.visible = false
}
const refreshTable = ()=>{
    ElMessage.success("导入成功！")
    closeUploadDialog()
    getTableData(true)
}

const handleBatchImport = () => {
  let obj = {
      0:{
        title:'批量上传审核结果',
        name:'现金兑换申请审核结果表',
        url:'/admin/order/batch_import_cash_review_result'
      } ,
      1:{
        title:'批量上传审核结果',
        name:'物品兑换申请审核结果表',
        url:'/admin/order/batch_import_product_review_result'
      }
    } 
  uploadObj.visible = true;
  uploadObj.title =  obj[moneyOrGoods.index].title;
  uploadObj.url =  obj[moneyOrGoods.index].url;
  uploadObj.downloadObj.name = obj[moneyOrGoods.index].name; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}${obj[moneyOrGoods.index].name}.xlsx`; // excel模板下载地址
}

getTableData(true);
</script>

<style lang="scss" scoped>
.layout-container-form {
  position: relative;
}

.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;

  .search-btn {
    margin-right: 10px;
    ;
  }
}

.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;
  margin-top: 10px;
}

.split-line {
  margin: 0 8px;
  color: #ccc;
}

.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
.cup{
    cursor: pointer;
}
.blue{
    color: #027db4;
}
</style>
